package com.eqxiu.ieditor.homepage.controller;

import com.eqxiu.ieditor.api.HomePageSceneServiceApi;
import com.eqxiu.ieditor.api.HomePageUserServiceApi;
import com.eqxiu.ieditor.api.controller.BaseApiController;
import com.eqxiu.ieditor.commons.web.ResultData;
import com.eqxiu.ieditor.dto.HomePageUserDTO;
import com.eqxiu.ieditor.dto.HomePageUserSceneDTO;
import com.eqxiu.ieditor.interceptor.UserContext;
import com.eqxiu.mall.marketing.api.MarketComponentSceneRelApi;
import com.eqxiu.scene.api.SceneServiceApi;
import com.eqxiu.scene.dto.SceneDTO;
import com.eqxiu.user.api.UserApi;
import com.eqxiu.user.api.dto.User;
import com.google.common.collect.Lists;
import eqxiu.passport.sdk.dto.UserDTO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * @ClassName HomePageMarketController
 * @escription 工作台增加微主页入口
 * @Author lifen
 * @Date 2019/9/18
 */
@RestController
@Api(description = "微主页作品信息入口")
@RequestMapping("api/m/homepageScene")
public class HomePageMarketController implements BaseApiController {
    private final Logger LOGGER = LoggerFactory.getLogger(HomePageSceneController.class);
    @Autowired
    private HomePageSceneServiceApi homePageSceneServiceApi;
    @Autowired
    private UserApi userApi;
    @Autowired
    private HomePageUserServiceApi homePageUserServiceApi;
    @Autowired
    private SceneServiceApi sceneServiceApi;
    @Autowired
    private MarketComponentSceneRelApi marketComponentSceneRelApi;


    private static final String HOMEPAGE_SCENE_STATUS_ON = "1";
    private static final String HOMEPAGE_SCENE_STATUS_OFF = "0";

    /**
     * @Description 查询该场景用户是否已经将他们加入到了微主页
     * @Author lifen
     * @Date 2019/9/18
     * @Param [userId, sceneIds]
     **/
    @RequestMapping("/checkHomePage")
    @ResponseBody
    @ApiOperation(value = "查询该场景是否用户已经把它加入到微主页")
    public ResultData check(@RequestParam(required = true) List<Integer> sceneIds) {
        UserDTO user = UserContext.getUser();
        if (user==null||user.getId()==null) {
            return fail().setMsg("userid can not be null");
        }
//        UserDTO user=new UserDTO();
//        user.setId("eqs10226063102106_weixin_qy");
        try {
            Map<String, Object> existSceneByUserId = homePageSceneServiceApi.isExistSceneByUserId(user.getId(), sceneIds);
            return success().setMap(existSceneByUserId);
        } catch (Exception e) {
            LOGGER.error(e.getMessage());
            return success().setObj(null);
        }
    }

    /**
     * @Description 根据场景ids批量移除作品-------目前没有使用
     * @Author lifen
     * @Date 2019/9/18
     * @Param [sceneIds]
     **/
    @RequestMapping("/batchRemove")
    @ResponseBody
    @ApiOperation(value = "根据场景id移除作品")
    public ResultData batchRemove(@RequestParam(required = true) List<Integer> sceneIds) {
        UserDTO user = UserContext.getUser();
        if (user==null||user.getId()==null) {
            return fail().setMsg("userid can not be null");
        }
        try {
            if (CollectionUtils.isNotEmpty(sceneIds)){
                homePageSceneServiceApi.batchRemoveHomePageScene(user.getId(),sceneIds);
            }
            return success();
        } catch (Exception e) {
            LOGGER.error(e.getMessage());
            return fail();
        }
    }
    /**
     * @Description 批量加入到微主页中
     * @Author lifen
     * @Date 2019/9/18
     * @Param [homePageSceneList]
     **/
    @RequestMapping("addHomePageScene")
    @ResponseBody
    @ApiOperation(value = "添加微主页作品")
    public ResultData addHomePageScene(@RequestBody ArrayList<HomePageUserSceneDTO> homePageSceneList) {
        UserDTO user = UserContext.getUser();
        if (user==null||user.getId()==null) {
            return fail().setMsg("userid can not be null");
        }
        try {
            if (homePageSceneList != null && homePageSceneList.size() > 0) {
                homePageSceneList.forEach(h->{
                    h.setUserId(user.getId());
                    h.setImgStr(h.getSceneCover());
                });
                homePageSceneServiceApi.addHomePageScene(homePageSceneList);
            }
            return success();
        } catch (Exception e) {
            LOGGER.error(e.getMessage());
            return fail();
        }
    }

    /**
     * @param sceneId 场景id
     * @param status  状态：1-开启；0-关闭
     * @return com.eqxiu.ieditor.commons.web.ResultData
     * @Author duan
     * @Description 微主页-开启/关闭
     * @Date 10:07 2019-09-18
     **/
    @RequestMapping(value = "/micro/enable", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(value = "开启/关闭 微主页")
    public ResultData microHomepageEnable(
            @ApiParam(value = "场景id") @RequestParam Long sceneId,
            @ApiParam(value = "状态：1-开启；0-关闭") @RequestParam String status) {

        UserDTO user = UserContext.getUser();
        String userId = user.getId();

        // 处理微主页用户信息
        HomePageUserDTO homePageUserDTO = new HomePageUserDTO();
        //获取用户基础信息
        User baseUser = userApi.getUser(userId);
        //判断微主页用户是否存在
        HomePageUserDTO checkHomePageUser = homePageUserServiceApi.queryHomePageUserMessage(userId);
        if (checkHomePageUser == null) {
            homePageUserDTO.setUserId(userId);
            homePageUserDTO.setPhone(baseUser.getPhone());
            homePageUserDTO.setLoginId(baseUser.getLoginName());
            homePageUserDTO.setLoginTime(new Date());
            homePageUserDTO.setUpdateTime(new Date());
            homePageUserDTO.setNickName(baseUser.getNick());
            //保存微主页用户
            homePageUserServiceApi.addHomePageUserMessage(homePageUserDTO);
            LOGGER.info("===保存微主页用户信息success===");
        }
        /**
         *处理作品信息
         **/
        //判断是开启还是移除
        if (HOMEPAGE_SCENE_STATUS_ON.equals(status)) {
            //开启
            // 如果已经开启过微主页，则不再开启
            Map<String, Object> existSceneByUserId = homePageSceneServiceApi.isExistSceneByUserId(userId, Lists.newArrayList(sceneId.intValue()));
            boolean exist = (boolean)existSceneByUserId.get(sceneId.toString());
            if (exist) {
                return success();
            }
            //获取场景基础信息
            SceneDTO scene = sceneServiceApi.getScene(sceneId);
            HomePageUserSceneDTO homePageUserSceneDTO = new HomePageUserSceneDTO();
            homePageUserSceneDTO.setUserId(userId);
            homePageUserSceneDTO.setSceneName(scene.getName());
            homePageUserSceneDTO.setSceneCode(scene.getCode());
            homePageUserSceneDTO.setSceneId(Integer.parseInt(String.valueOf(sceneId)));
            homePageUserSceneDTO.setCreateTime(new Date());
            homePageUserSceneDTO.setUpdateTime(new Date());
            homePageUserSceneDTO.setProperty(scene.getProperty());
            homePageUserSceneDTO.setImgStr(scene.getCover());
            homePageUserSceneDTO.setSort(1000);
            homePageUserSceneDTO.setType(2);
            homePageUserSceneDTO.setPlatform(1);
            ArrayList<HomePageUserSceneDTO> homePageUserSceneDTOS = new ArrayList<>();
            homePageUserSceneDTOS.add(homePageUserSceneDTO);
            //保存微主页作品
            homePageSceneServiceApi.addHomePageScene(homePageUserSceneDTOS);
            LOGGER.info("===保存微主页作品信息success===");
        } else if (HOMEPAGE_SCENE_STATUS_OFF.equals(status)) {
            //关闭
            homePageSceneServiceApi.deleteHomePageScene(Integer.parseInt(String.valueOf(sceneId)));
            // 查看该作品是否有开启相关的组件，如果开启则关闭掉
            marketComponentSceneRelApi.updateStatusBySceneId(sceneId, Byte.valueOf(HOMEPAGE_SCENE_STATUS_OFF));
            LOGGER.info("===移除微主页作品信息success===");
        }
        return success();
    }
}
